import React, { useEffect, useState } from 'react';
import { message, Input } from 'antd';
import CustomForm from '../../../../../../components/CustomForm';
import services from '../../../../../../services/api';

const VersionSwitch = (props) => {
  const { record, value, queryList, closeModal } = props;
  const [currVersion, setCurrVersion] = useState('');
  let form = null;

  useEffect(() => {
    getInterfaceCurrentInfo();
  }, []);

  const getInterfaceCurrentInfo = async () => {
    const { data, code, msg } = await services.history.currVersion(record.id);
    if (code) return message.error(msg);
    setCurrVersion(data);
  };

  const handleSubmit = () => {
    form.validateFields(async (errors, { desc }) => {
      if (!errors) {
        const { code, msg } = await services.history.switchVersion({ id: value.id, snapshotId: record.id, desc });
        if (code) return message.error(msg);
        message.success(msg);
        closeModal();
        queryList();
      }
    });
  };

  const getFormItems = () => {
    const { version } = record;
    const { name } = value;
    return [
      {
        label: {
          label: '切换接口名',
          className: 'tantuer-form-item3 tantuer-form-item-nowrap',
        },
        name: 'name',
        options: {
          initialValue: name,
        },
        component: <Input disabled />,
      },
      {
        label: {
          label: '当前版本',
          className: 'tantuer-form-item3 tantuer-form-item-nowrap',
        },
        name: 'currVersion',
        options: {
          initialValue: currVersion || '-',
        },
        component: <Input disabled />,
      },
      {
        label: {
          label: '切换至版本',
          className: 'tantuer-form-item3 tantuer-form-item-nowrap',
        },
        name: 'version',
        options: {
          initialValue: version,
        },
        component: <Input disabled />,
      },
      {
        label: {
          label: '发布备注',
          className: 'tantuer-form-item3 tantuer-form-item-nowrap',
        },
        name: 'desc',
        options: {
          initialValue: '',
          rules: [
            { required: true, message: '请输入发布备注', },
            { max: 256, message: '最长256个字符' }
          ],
        },
        component: <Input.TextArea placeholder='请输入' />,
      },
    ];
  };

  return (
    <CustomForm
      formItems={getFormItems()}
      closeModal={closeModal}
      onHandleSubmit={handleSubmit}
      createForm={(ref) => (form = ref)}
      colNum={1}
    />
  );
};

export default VersionSwitch;
